'use strict';
var express = require('express');
var fs = require("fs");
var path = require('path');
var http = require('http');
var url = require('url');
var _ = require('underscore');
var qs=require('querystring');
var moment = require('moment');
var sqlite3 = require("sqlite3");
var sqlHelper= require('./sqlite3help');
var fileKit= require('./file-kit');
var app = express();
var multer  = require('multer');//文件上传
var upload = multer({dest:'upload/'}).any();
var jwt = require('jsonwebtoken');//用来创建和确认用户信息摘要
var util = require('util');
var config = require('./conf/config');//读取配置文件config.js信息
var port = process.env.PORT || config.port;        // set our port
var router = express.Router(); 
app.set('superSecret', config.jwtsecret); 
var EventProxy = require('eventproxy');
var bodyParser = require('body-parser');
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (req.method == 'OPTIONS') {
    res.send(200); /让options请求快速返回/
  }else {
    next();
  }
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/uploads'));
router.get('/auth/login', function(req, response) {
	var username=req.body.username ||req.query.username;
	var password=req.body.password ||req.query.password;
	var post_data = {username:username,md5pwd:password};
	var content=qs.stringify(post_data);
	console.log("headers: ", password);
	var options = {
		host: '192.168.1.221',
		port: 8380,
		path: '/checkStaff.do',
		method: 'POST',
		headers:{
		  'Content-Type':'application/x-www-form-urlencoded',
		  'Content-Length':content.length
		}
	};
	var req=http.request(options, function (res) {
		console.log("statusCode: ", res.statusCode);
		var json='';
		res.on('data', function (body) {
			json += body;
		});
		res.on('end',function(){
			//获取到的数据
			var result = JSON.parse(json);
			if(0==result.errorCode){
				//var expiresIn=60 * 60 ;
				//var token = jwt.sign({ foo: 'bar' }, app.get('superSecret'),{ expiresIn: expiresIn });
				//result.expiredAt=expiresIn;
				//console.log(token);
			}
			response.json({success:true,httpstatus:200,result:result});  
		});
	}).on('error', function (e) {
		console.error(e);
	});
	req.write(content);
	req.end();
});
router.use(function(req, res, next) {
	 var token = req.body.token || req.query.token || req.headers['x-access-token'];
	if (token) {
		//console.log(app.get('superSecret'));   
		/**
		 jwt.verify(token, app.get('superSecret'), function(err, decoded) {
            if (err) {
				console.log('err---',err);   
                return res.json({ success: false,httpstatus:403, message: 'token信息错误.' });
            } else {
                // 如果没问题就把解码后的信息保存到请求中，供后面的路由使用
                req.decoded = decoded;
                next();
            }
        });
		**/
		 next();
	}else{
		 return res.status(403).send({
            success: false,
			httpstatus:403 ,
            message: '没有提供token！或者权限被拒绝'
        });

	}
});


router.get('/carfile**', function(req, res) {
	var current_page = 1; //默认为1
    var num = 3000; //一页条数
	var name=req.query.name;
	if(!name){
	  name='';
	}
	var sort=req.query.sort;
	var order=req.query.order;
	var db = new sqlite3.Database(config.database);
	var urlPath=decodeURIComponent(req.path);
	urlPath=urlPath.replace(/(\/*$)/g,"");
	var obj={name:req.query.name,path:urlPath};
	sqlHelper.query(db,obj,sort,order,function(error,rows){
		var result={};
		result.content=rows;
		res.json({success:true,httpstatus:200,result:result}); 
	});
});
router.get('/company**', function(req, res) {
    var current_page = 1; //默认为1
    var num = 3000; //一页条数
	var name=req.query.name;
	if(!name){
	  name='';
	}
	var sort=req.query.sort;
	var order=req.query.order;
	var db = new sqlite3.Database(config.database);
	var urlPath=decodeURIComponent(req.path);
	urlPath=urlPath.replace(/(\/*$)/g,"");
	var obj={name:req.query.name,path:urlPath};
	sqlHelper.query(db,obj,sort,order,function(error,rows){
		var result={};
		result.content=rows;
		res.json({success:true,httpstatus:200,result:result}); 
	}); 	
});
router.get('/ftpshare**', function(req, res) {
  var current_page = 1; //默认为1
    var num = 3000; //一页条数
	var name=req.query.name;
	if(!name){
	  name='';
	}
	var sort=req.query.sort;
	var order=req.query.order;
	var db = new sqlite3.Database(config.database);
	var urlPath=decodeURIComponent(req.path);
	urlPath=urlPath.replace(/(\/*$)/g,"");
	var obj={name:req.query.name,path:urlPath};
	sqlHelper.query(db,obj,sort,order,function(error,rows){
		var result={};
		result.content=rows;
		res.json({success:true,httpstatus:200,result:result}); 
	}); 
});
router.get('/carphoto**', function(req, res) {
     var current_page = 1; //默认为1
    var num = 3000; //一页条数
	var name=req.query.name;
	if(!name){
	  name='';
	}
	var sort=req.query.sort;
	var order=req.query.order;
	var db = new sqlite3.Database(config.database);
	var urlPath=decodeURIComponent(req.path);
	urlPath=urlPath.replace(/(\/*$)/g,"");
	var obj={name:req.query.name,path:urlPath};
	sqlHelper.query(db,obj,sort,order,function(error,rows){
		var result={};
		result.content=rows;
		res.json({success:true,httpstatus:200,result:result}); 
	});   
});
router.get('/common**', function(req, res) {
     var current_page = 1; //默认为1
    var num = 3000; //一页条数
	var name=req.query.name;
	if(!name){
	  name='';
	}
	var sort=req.query.sort;
	var order=req.query.order;
	var db = new sqlite3.Database(config.database);
	var urlPath=decodeURIComponent(req.path);
	urlPath=urlPath.replace(/(\/*$)/g,"");
	var obj={name:req.query.name,path:urlPath};
	sqlHelper.query(db,obj,sort,order,function(error,rows){
		var result={};
		result.content=rows;
		res.json({success:true,httpstatus:200,result:result}); 
	});   
});

router.post('/rename/:fileId', function(req, res) {
	var fileId=req.params.fileId;
	var fileName=req.body.fileName || req.query.fileName;
	if(!fileId||!fileName){
	  res.json({success:true,httpstatus:404,result:false}); 
	  return;
	}
	var db = new sqlite3.Database(config.database);
	sqlHelper.get(db,fileId,function(error,row){
		if(!row){
		  res.json({success:true,httpstatus:404,result:false}); 
		  return;	
		}
		//文件重命名
		var fullPath=row.rel_path;
		fs.stat(fullPath, function (err, stats){
			if(err){
				if("ENOENT"==err.code){
					//文件可能已经不存在啦，直接删除掉索引记录
					res.json({success:true,httpstatus:200,result:true}); 	
				}
				return;
			}
			if (stats.isDirectory()){
				var dirpath=path.dirname(fullPath);
			    var newPath=dirpath+path.sep+fileName;
				fs.rename(fullPath,newPath,function(err ){	
					if(!err){
						sqlHelper.updatePath(row,fileName,function(error){
							if(!error){
								console.log(error);	
							}	
						});
					  res.json({success:true,httpstatus:200,result:true}); 
					}
				});
			}else if (stats.isFile()){
			  var dirpath=path.dirname(fullPath);
			  var ext = path.extname(fullPath).substr(1);
			  var newPath=dirpath+path.sep+fileName;
			  fs.rename(fullPath,newPath,function(err ){	
				if(!err){
					//更新数据
					row.name=fileName;
					row.rel_path=newPath;
					row.mtime=Date.now();
					sqlHelper.rename(db,row,function(error){
						if(!error){
							console.log(error);	
						}		
					});
					res.json({success:true,httpstatus:200,result:true}); 	
				}
			  });
			}
		
		});
		
		

	});
});
router.post('/unlink/:fileId', function(req, res) {
	var fileId=req.params.fileId;
	if(!fileId){
	  res.json({success:true,httpstatus:404,result:false}); 
	  return;
	}
	var db = new sqlite3.Database(config.database);
	sqlHelper.get(db,fileId,function(error,row){
		if(!row){
		  res.json({success:true,httpstatus:404,result:false}); 
		  return;	
		}
		//删除文件
		var fullPath=row.rel_path
		fs.stat(fullPath, function (err, stats){
			if(err){
				if("ENOENT"==err.code){
					//文件可能已经不存在啦，直接删除掉索引记录
					sqlHelper.del(db,row.id,function(error){
						console.log(error);	
					});
					res.json({success:true,httpstatus:200,result:true}); 	
				}
				return;
			}
			if (stats.isDirectory()){
				var obj={path:row.path+"/"+row.name };
				//文件夹必需为空夹
				sqlHelper.count(db,obj,function(error,total){
					if(total&&total.totalCount&&total.totalCount==0){
						console.log("totalCount"+totalCount);	
					  fs.rmdir(fullPath,function(err){
							if(!err){
							//更新数据
							// res.json({success:true,httpstatus:200,result:true}); 
							}
						});
					   res.json({success:true,httpstatus:200,result:true}); 
					}else{
						res.json({success:true,httpstatus:403,result:false}); 
						return;
					}
				}); 
				
			}else if (stats.isFile()){
			  fs.unlink(fullPath,function(err ){
				if(!err){
					//更新数据
					sqlHelper.del(db,row.id,function(error){	
					console.log(error);	
					});
					res.json({success:true,httpstatus:200,result:true}); 	
				}
			  });
			}
		});
		

	});
});
router.post('/mkdir', function(req, res) {
	var fileDirPath = req.body.dirPath || req.query.dirPath ;
	var fileName=req.body.fileName || req.query.fileName;
	if (!fileDirPath||!fileName) {
		  res.json({success:true,httpstatus:404,result:false});  
		  return;
	}
	var db = new sqlite3.Database(config.database);
	//判断是否为根路径
	fileDirPath=fileDirPath.replace(/\\/g,"\/");
	fileDirPath=fileDirPath.replace(/(\/*$)/g,"");//剃掉最后以为的‘/’
	var filepaths=fileDirPath.split('/');
	if(filepaths.length==2){
		fileDirPath=filepaths[1];
	}
	if(config.filePath.hasOwnProperty(fileDirPath)){
		var rootKey=fileDirPath;
		var rootPath=config.filePath[fileDirPath];
		var relPath=rootPath+path.sep+fileName;
		var ep = new EventProxy();
		mkdir(relPath,rootKey,rootPath,ep);	
		ep.all('file', 'db', function (file, db) {
			if(!file&&!db){
				res.json({success:true,httpstatus:200,result:true}); 
			}else{
				res.json({success:true,httpstatus:200,result:false}); 
			}
		});
	}else{
	  sqlHelper.getByPath(db,fileDirPath,function(error,obj){
		if(obj){
			var relPath=obj.rel_path+path.sep+fileName;
			var ep = new EventProxy();
			var rootKey=obj.root;
			var rootPath=config.filePath[rootKey];
			mkdir(relPath,rootKey,rootPath,ep);	
			ep.all('file', 'db', function (file, db) {
				if(!file&&!db){
					res.json({success:true,httpstatus:200,result:true}); 
				}else{
					res.json({success:true,httpstatus:200,result:false}); 
				}
			});

		
		}
	   });
	}
});
var mkdir=function(relPath,rootKey,rootPath,ep){
	fs.mkdir(relPath,(err)=>{
	    ep.emit('file',err);
		var stats=fs.statSync(relPath, function (err, stats){});
		var result= fileKit.getResult(stats,relPath,rootKey,rootPath); 
		var db = new sqlite3.Database(config.database);
		sqlHelper.add(db,result,function(error,obj){
		  ep.emit('db',error); 
		});
	});	 
};
//全局搜索功能
router.get('/search', function(req, res) {
	var current_page = 1; //默认为1
    var num = 3000; //一页条数
//	console.log(req.query.name);
	var name=req.query.name;
	var sort=req.query.sort;
	var order=req.query.order;
	if(!name||name.trim().length<=0){
	  var result={};
	  result.content=[];
	  res.json({success:true,httpstatus:200,result:result}); 
	  return;
	}
	var db = new sqlite3.Database(config.database);
	var obj={name:req.query.name};
	
	sqlHelper.search(db,obj,sort,order,function(error,rows){
		var result={};
		result.content=rows;
		res.json({success:true,httpstatus:200,result:result}); 
	});
});
//文件下载
router.get('/download/:fileId', function(req, res) {
	var fileId=req.params.fileId;
	if(!fileId){
	  res.json({success:true,httpstatus:404,result:false}); 
	  return;
	}
	var db = new sqlite3.Database(config.database);
	sqlHelper.get(db,fileId,function(error,row){
		if(!row){
		  res.json({success:true,httpstatus:404,result:false}); 
		  return;	
		}
		var realpath=row.rel_path;
		var filename=row.name;
		res.download(realpath,filename);
	});
});


app.use('/api/v1/', router);
app.use(express.static(__dirname + '/public'));
app.get("/",function(){
	this.redirect("/index.html");
});
router.post('/file-upload',function(req,res){
	var fileDirPath = req.body.dirPath || req.query.dirPath ;
	console.log("---------访问上传路径-------------"+fileDirPath); 
	if (!fileDirPath) {
		res.json({success:true,httpstatus:404,result:false});  
	    return;
	}
    upload(req, res, function (err) {
		//添加错误处理
		if (err) {
		  console.log(err);
		  res.json({success:true,httpstatus:404,result:false}); 
		  return;
		} 
		  //判断是否为根路径
		fileDirPath=fileDirPath.replace(/\\/g,"\/");
		fileDirPath=fileDirPath.replace(/(\/*$)/g,"");//剃掉最后以为的‘/’
		var filepaths=fileDirPath.split('/');
		if(filepaths.length==2){
			fileDirPath=filepaths[1];
		}
		req.file = req.files[0];
		var tmp_path = req.file.path;  
		if(config.filePath.hasOwnProperty(fileDirPath)){
			var rootKey=fileDirPath;
			var rootPath=config.filePath[rootKey];
			var target_path = rootPath + req.file.originalname;
			var ep = new EventProxy();
			addFile(tmp_path,target_path,rootKey,rootPath,ep);	
			ep.all('file', 'db', function (file, db) {
				if(!file&&!db){
					res.json({success:true,httpstatus:200,result:true}); 
				}else{
					res.json({success:true,httpstatus:200,result:false}); 
				}
			});
	
		}else{
			var db = new sqlite3.Database(config.database);
		  	sqlHelper.getByPath(db,fileDirPath,function(error,obj){ 
				if(obj){
				  var rootKey=obj.root;
				  var rootPath=config.filePath[rootKey];
				  var target_path=obj.rel_path+path.sep+req.file.originalname;
				  var ep = new EventProxy();
				  addFile(tmp_path,target_path,rootKey,rootPath,ep);
				  ep.all('file', 'db', function (file, db) {
					  if(!file&&!db){
							res.json({success:true,httpstatus:200,result:true}); 
					  }else{
							res.json({success:true,httpstatus:200,result:false}); 
					  }					  
				  }); 
				}
		   }); 

		}
    }); 
});

var addFile=function(tmp_path,target_path,rootKey,rootPath,ep){
	var exist=fs.existsSync(target_path);
	while(exist){
		target_path=fileKit.getFileName(target_path);
		exist=fs.existsSync(target_path);
	}
	fs.rename(tmp_path,target_path,function(err){
		ep.emit('file',err);
		if(!err){
			var stats=fs.statSync(target_path, function (err, stats){});
			var result= fileKit.getResult(stats,target_path,rootKey,rootPath); 
			var db = new sqlite3.Database(config.database);
			sqlHelper.add(db,result,function(error,obj){
				ep.emit('db',error); 
			});
		}
	});		
}


app.use(function (req, res, next) {
   // var err = new Error(req.path+'Not Found');
   // err.status = 404;
	//next(err);
});
app.listen(port, function () {
  console.log('app is listening at port: '+port);
});
